import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter2/http/api.dart';
import 'package:flutter2/http/dio_manager.dart';
import 'package:flutter2/item/item_order.dart';
import 'package:flutter2/model/order_entity.dart';
import 'package:flutter2/ui/home.dart';
import 'package:flutter2/ui/tab.dart';

class OrderPage extends StatefulWidget {
  const OrderPage({super.key});

  @override
  State<OrderPage> createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> with AutomaticKeepAliveClientMixin {
  final EasyRefreshController _controller = EasyRefreshController(controlFinishRefresh: true);
  final List<OrderEntity> _list = [];

  @override
  void initState() {
    super.initState();
    getData();
    notifier.addListener(() {
      getData();
    });
    tabNotifier.addListener(() {
      if (tabNotifier.value == 0) {
        // getData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SafeArea(
      child: EasyRefresh(
        controller: _controller,
        onRefresh: () {
          getData(showLoading: false);
        },
        child: ListView.builder(
          itemBuilder: (context, index) {
            var order = _list[index];
            return ItemOrder(order);
          },
          itemCount: _list.length,
        ),
      ),
    );
  }

  getData({bool showLoading = true}) {
    DioManager.request<List<OrderEntity>>(
      showLoading: showLoading,
      path: HttpApi.orderList,
      onSuccess: (data) {
        _list.clear();
        _list.addAll(data ?? []);
        setState(() {});
      },
      onFinish: () {
        _controller.finishRefresh();
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}
